package com.care.inquiry.server.im;


import com.care.inquiry.server.im.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version: java version 1.8
 * @author: cuiweijie
 * @date: 2024-03-25 15:11
 */
public class IMServer {

    public static final Map<String, Channel> USERS =new ConcurrentHashMap<>(1024);

    public static void start() throws Exception {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        //绑定端口
        ServerBootstrap bootstrap = new ServerBootstrap();
                    //把两个线程池放进去
        bootstrap.group(boss,worker)
                //指定一个channel来封装我们的ServerSocketChannel
                .channel(NioServerSocketChannel.class)
                //初始化 chilidHandle
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //添加Http编码解释器
                        //将HttpServerCodec添加到pipeline中，用于将HTTP请求解码为HTTP对象
             pipeline.addLast(new HttpServerCodec())
                                //将ChunkedWriteHandler添加到pipeline中，用于将HTTP对象编码为HTTP响应
                                .addLast(new ChunkedWriteHandler())
                                //对http消息聚合  FullHttpRequest、FullHttpResponse
                                .addLast(new HttpObjectAggregator(1024*64))
                                //http和websocket协议的支持
                                .addLast(new WebSocketServerProtocolHandler("/"))
                                .addLast(new WebSocketHandler());
                    }
                });

        //绑定我们的端口号
        bootstrap.bind(9401).sync();





    }


}
